<template>
  <el-dialog
    center
    :close-on-click-modal="false"
    v-model="dialogBindVisible"
    title="分配设备"
    :before-close="handleClose"
  >
    <el-tabs v-model="tab" type="card" class="demo-tabs">
      <el-tab-pane key="1" label="未绑定设备" name="1">
        <div class="datatable">
          <el-table
            :data="unBindDeviceList"
            border
            style="width: 100%; box-sizing: border-box"
            @selection-change="selectDevice"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column
              prop="sn"
              :label="t(`module.table.Imei`)"
              :align="'center'"
              width="120"
            />
            <el-table-column
              prop="name"
              :label="t(`module.table.Nickname`)"
              :align="'center'"
              width="120"
            />
          </el-table>
          <el-row :gutter="20">
            <el-col :span="10" :offset="10">
              <el-pagination
                small
                background
                layout="prev, pager, next"
                :total="total"
                class="mt-4"
                @current-change="changeDevicePage"
                :current-page="devicePage"
              ></el-pagination>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
      <el-tab-pane key="2" label="已绑定设备" name="2">
        <div class="datatable">
          <el-table
            :data="hasBindDeviceList"
            border
            style="width: 100%; box-sizing: border-box"
          >
            <el-table-column
              prop="sn"
              :label="t(`module.table.Imei`)"
              :align="'center'"
              width="120"
            />
            <el-table-column
              prop="name"
              :label="t(`module.table.Nickname`)"
              :align="'center'"
              width="120"
            />
            <el-table-column
              :label="t(`module.table.Handle`)"
              :align="'center'"
              width="120"
            >
              <template #default="scope">
                <el-row>
                  <el-col :span="6"
                    ><el-popconfirm
                      @confirm="unBind(scope.row.id)"
                      title="Are you sure to un bind this?"
                    >
                      <template #reference>
                        <el-button type="warning">解除绑定</el-button>
                      </template>
                    </el-popconfirm></el-col
                  >
                </el-row>
              </template>
            </el-table-column>
          </el-table>
          <el-row :gutter="20">
            <el-col :span="10" :offset="10">
              <el-pagination
                small
                background
                layout="prev, pager, next"
                :total="total"
                class="mt-4"
                @current-change="changeHasBindDevicePage"
                :current-page="hasBindDevicePage"
              ></el-pagination>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
    </el-tabs>
    <template #footer v-if="tab == '1'">
      <span class="dialog-footer">
        <el-button @click="cancelBind">取消</el-button>
        <el-button type="primary" @click="submitBind">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { reactive, onMounted, toRefs, watch } from "vue";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
import API from "api";
export default {
  props: {
    selectedUserId: Number,
    showDialog: Boolean,
  },
  emits: ["closeDialog"],
  setup(props, ctx) {
    const { t } = useI18n();
    let state = reactive({
      unBindDeviceList: [],
      hasBindDeviceList: [],
      hasBindDevicePage: 1,
      unBindDevicePage: 1,
      selectedDevice: [],
      selectedUserId: 0,
      tab: "1",
      dialogBindVisible: false,
    });
    onMounted(() => {
      initUnBindDeviceList();
      initHasBindDeviceList();
    });

    watch(
      () => props.showDialog,
      (val) => {
        state.dialogBindVisible = val;
        state.selectedDevice = [];
      }
    );
    const refreshList = () => {
      state.unBindDevicePage = 1;
      state.hasBindDevicePage = 1;
      initUnBindDeviceList();
      initHasBindDeviceList();
    };
    const submitBind = () => {
      API.bind({
        user_id: props.selectedUserId,
        device_ids: state.selectedDevice,
      }).then((res) => {
        if (res.code == 0) {
          ElMessage.success("succcess");
          state.dialogBindVisible = false;
          refreshList()
          ctx.emit("closeDialog");
        } else {
          ElMessage.error(res.msg);
        }
      });
    };

    const cancelBind = () => {
      state.selectedDevice = [];
      state.dialogBindVisible = false;
      ctx.emit("closeDialog");
    };

    const unBind = (id) => {
      API.unBind({ user_id: props.selectedUserId, device_ids: [id] }).then(
        (res) => {
          if (res.code == 0) {
            state.dialogBindVisible = false;
            ElMessage.success("success");
            refreshList()
            ctx.emit("closeDialog");
          } else {
            ElMessage.error(res.msg);
          }
        }
      );
    };

    const changeUnBindDevicePage = (page) => {
      state.unBindDevicePage = page;
      initUnBindDeviceList();
    };

    const changeHasBindDevicePage = (page) => {
      state.hasBindDevicePage = page;
      initHasBindDeviceList();
    };

    const initUnBindDeviceList = () => {
      API.deviceList({ page: state.unBindDevicePage, un_bind: 1 }).then(
        (res) => {
          state.unBindDeviceList = res.data.list;
        }
      );
    };
    const initHasBindDeviceList = () => {
      API.deviceList({ page: state.hasBindDevicePage }).then((res) => {
        state.hasBindDeviceList = res.data.list;
      });
    };
    const selectDevice = (row) => {
      // state.form.task_ids = []
      if (row.length > 0) {
        row.forEach((element) => {
          state.selectedDevice.push(element.id);
        });
      }
    };
    const handleClose = () => {
      ctx.emit("closeDialog");
    };
    return {
      submitBind,
      cancelBind,
      changeUnBindDevicePage,
      changeHasBindDevicePage,
      selectDevice,
      unBind,
      t,
      handleClose,
      ...toRefs(state),
    };
  },
};
</script>

<style lang="scss" scoped>
.title {
  display: block;
  padding: 2rem 1rem;
  font-size: 2rem;
  font-weight: bolder;
  text-align: left;
}
.search {
  display: flex;
  width: 30rem;
  padding: 1rem;
}
.datatable {
  box-sizing: border-box;
  padding: 0.625rem;
}
.ml-1 {
  margin-left: 1rem;
}
</style>
